/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.home.modular.structure.group.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.home.core.enums.HomeBuildInEnum;
import vip.xiaonuo.home.modular.structure.group.param.*;
import vip.xiaonuo.home.modular.structure.org.entity.HomeOrg;
import vip.xiaonuo.home.modular.structure.org.service.HomeOrgService;
import vip.xiaonuo.home.modular.structure.user.entity.HomeUser;
import vip.xiaonuo.home.modular.structure.user.service.HomeUserService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.home.modular.structure.group.entity.HomeGroup;
import vip.xiaonuo.home.modular.structure.group.mapper.HomeGroupMapper;
import vip.xiaonuo.home.modular.structure.group.service.HomeGroupService;
import vip.xiaonuo.sys.api.SysGroupApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户组Service接口实现类
 *
 * @author yubaoshan
 * @date  2024/12/24 03:33
 **/
@Service
public class HomeGroupServiceImpl extends ServiceImpl<HomeGroupMapper, HomeGroup> implements HomeGroupService {

    @Resource
    private SysGroupApi sysGroupApi;

    @Resource
    private HomeUserService homeUserService;

    @Resource
    private HomeOrgService homeOrgService;

    @Override
    public Page<HomeGroup> page(HomeGroupPageParam homeGroupPageParam) {
        QueryWrapper<HomeGroup> queryWrapper = new QueryWrapper<HomeGroup>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(homeGroupPageParam.getName())) {
            queryWrapper.lambda().like(HomeGroup::getName, homeGroupPageParam.getName());
        }
        //数据归属
        queryWrapper.lambda().eq(HomeGroup::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(homeGroupPageParam.getSortField(), homeGroupPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(homeGroupPageParam.getSortOrder());
            queryWrapper.orderBy(true, homeGroupPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(homeGroupPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(HomeGroup::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(HomeGroupAddParam homeGroupAddParam) {
        HomeGroup homeGroup = BeanUtil.toBean(homeGroupAddParam, HomeGroup.class);
        //数据归属
        homeGroup.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        this.save(homeGroup);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(HomeGroupEditParam homeGroupEditParam) {
        HomeGroup homeGroup = this.queryEntity(homeGroupEditParam.getId());
        BeanUtil.copyProperties(homeGroupEditParam, homeGroup);
        this.updateById(homeGroup);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<HomeGroupIdParam> homeGroupIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(homeGroupIdParamList, HomeGroupIdParam::getId));
    }

    @Override
    public HomeGroup detail(HomeGroupIdParam homeGroupIdParam) {
        return this.queryEntity(homeGroupIdParam.getId());
    }

    @Override
    public HomeGroup queryEntity(String id) {
        HomeGroup homeGroup = this.getById(id);
        if(ObjectUtil.isEmpty(homeGroup)) {
            throw new CommonException("用户组不存在，id值为：{}", id);
        }
        return homeGroup;
    }

    @Override
    public List<String> ownUser(HomeGroupIdParam sysGroupIdParam) {
        return sysGroupApi.ownUser(sysGroupIdParam.getId());
    }

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<HomeOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        // 定义机构集合
        Set<HomeOrg> homeOrgSet = CollectionUtil.newHashSet();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<HomeOrg> allOrgList = homeOrgService.list();
            loginUserDataScope.forEach(orgId -> homeOrgSet.addAll(homeOrgService.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = homeOrgSet.stream().map(HomeOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(HomeOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(HomeOrg::getSortCode);
        List<HomeOrg> homeOrgList = homeOrgService.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = homeOrgList.stream().map(homeOrg ->
                        new TreeNode<>(homeOrg.getId(), homeOrg.getParentId(), homeOrg.getName(), homeOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<HomeUser> userSelector(HomeGroupSelectorUserParam homeGroupSelectorUserParam) {
        LambdaQueryWrapper<HomeUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(HomeUser::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 只查询部分字段
        lambdaQueryWrapper.select(HomeUser::getId, HomeUser::getAvatar, HomeUser::getOrgId, HomeUser::getPositionId, HomeUser::getAccount,
                HomeUser::getName, HomeUser::getSortCode, HomeUser::getGender, HomeUser::getEntryDate);
        if (ObjectUtil.isNotEmpty(homeGroupSelectorUserParam.getOrgId())) {
            // 如果机构id不为空，则查询该机构及其子机构下的所有人
            List<String> childOrgIdList = CollStreamUtil.toList(homeOrgService.getChildListById(homeOrgService
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), homeGroupSelectorUserParam.getOrgId(), true), HomeOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                lambdaQueryWrapper.in(HomeUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
        }
        // 排除超管
        lambdaQueryWrapper.ne(HomeUser::getAccount, HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        //需要排除自己
        lambdaQueryWrapper.ne(HomeUser::getId, StpLoginUserUtil.getLoginUser().getId());
        if (ObjectUtil.isNotEmpty(homeGroupSelectorUserParam.getSearchKey())) {
            lambdaQueryWrapper.like(HomeUser::getName, homeGroupSelectorUserParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(HomeUser::getSortCode);
        return homeUserService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    @Override
    public void grantUser(HomeGroupGrantUserParam homeGroupGrantUserParam) {
        sysGroupApi.grantUser(homeGroupGrantUserParam.getId(), homeGroupGrantUserParam.getGrantInfoList());
    }
}
